package com.lk.template.exception;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常拦截
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(Exception.class)
  public R doError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception ex) {
    Map<String, Object> responseData = new HashMap<>(16);
    if (ex instanceof CommonException) {
      CommonException commonException = (CommonException) ex;
      responseData.put("errCode", commonException.getErrCode());
      responseData.put("errMsg", commonException.getErrMsg());
      responseData.put("serviceName", commonException.getServiceName());
      log.error(commonException.getErrMsg(), commonException);
    } else {
      responseData.put("errCode", EmError.UNKNOWN_ERROR.getErrCode());
      responseData.put("errMsg", EmError.UNKNOWN_ERROR.getErrMsg());
      responseData.put("serviceName", EmError.UNKNOWN_ERROR.getServiceName());
      log.error(EmError.UNKNOWN_ERROR.getErrMsg(), ex);
    }
    return R.error(responseData);
  }
}
